package com.weishi.project.training.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weishi.common.utils.DateUtils;
import com.weishi.common.utils.StringUtils;
import com.weishi.project.training.domain.*;
import com.weishi.project.training.mapper.HeartRateRecordMapper;
import com.weishi.project.training.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 心率计次数据Service业务层处理
 */
@Service
public class HeartRateRecordServiceImpl extends ServiceImpl<HeartRateRecordMapper, HeartRateRecord> implements IHeartRateRecordService {

    @Autowired
    private HeartRateRecordMapper heartRateRecordMapper;

    @Autowired
    private IHeartRateCountService heartRateCountService;

    @Autowired
    private IHeartRateService heartRateService;

    @Autowired
    private ITrainingAchievementService trainingAchievementService;

    @Autowired
    private ITrainingGroupChannelService trainingGroupChannelService;

    /**
     * 查询心率计次数据列表
     */
    @Override
    public List<HeartRateRecord> selectHeartRateRecordList(HeartRateRecord heartRateRecord) {
        return heartRateRecordMapper.selectHeartRateRecordList(heartRateRecord);
    }

    @Override
    public List<HeartRateRecord> selectByMap(Map<String, Object> heartRateParams) {
        return heartRateRecordMapper.selectByMap(heartRateParams);
    }

    @Override
    public void removeByHeartRateCountId(Integer heartRateCountId) {
        heartRateRecordMapper.removeByHeartRateCountId(heartRateCountId);
    }

    @Override
    public void addRecord(Integer channelId) {
        TrainingGroupChannel channel = trainingGroupChannelService.getById(channelId);
        long fristTime = channel.getStime()!=null?channel.getStime().getTime() : 0L;

        //每个运动员的分段心率
        Map<Integer,List<Integer>> sportHeartRate = new HashMap<>();

        List<HeartRateCount> heartRateCounts = heartRateCountService.qryCountByChannel(channelId);

        long startTime = fristTime;

        if(heartRateCounts!=null && heartRateCounts.size()>0){
            for(HeartRateCount count : heartRateCounts){
                HeartRateRecord params = new HeartRateRecord();
                params.setHeartRateCountId(count.getId());
                List<HeartRateRecord> heartRateRecords = heartRateRecordMapper.selectHeartRateRecordList(params);
                long endTimp = fristTime + DateUtils.getLongTime(count.getPointAchievement());

                for(HeartRateRecord heartRateRecord : heartRateRecords){

                    HeartRate paramsq = new HeartRate();
                    paramsq.setChannelId(channelId);
                    params.setSportsmanId(heartRateRecord.getSportsmanId());
                    List<HeartRate> heartRates = heartRateService.selectHeartRateList(paramsq);

                    aggregatedData(heartRateRecord,heartRates,fristTime,startTime,endTimp);
                    heartRateRecordMapper.updateById(heartRateRecord);

                    List<Integer> temp = sportHeartRate.get(heartRateRecord.getSportsmanId());
                    if(temp==null){
                        temp = new ArrayList<>();
                        sportHeartRate.put(heartRateRecord.getSportsmanId(),temp);
                    }
                    temp.add(heartRateRecord.getHeartRateAvg());
                }

                startTime = endTimp;
            }

        }

        //更新成绩表
        for(Integer sportsmanId : sportHeartRate.keySet()){
            List<Integer> heartRates = sportHeartRate.get(sportsmanId);
            StringBuffer heartRateAvg = new StringBuffer();
            for(Integer heartRate : heartRates){
                if(heartRate==null){
                    heartRate = 0;
                }
                heartRateAvg.append(heartRate).append(" ");
            }
            trainingAchievementService.update(Wrappers.<TrainingAchievement>lambdaUpdate()
                    .set(TrainingAchievement::getHeartRate, StringUtils.isEmpty(heartRateAvg) ? 0 : heartRateAvg.toString().trim())
                    .eq(TrainingAchievement::getChannelId , channelId)
                    .eq(TrainingAchievement::getSportsmanId , sportsmanId));
        }
    }

    /**
     * 合计心率详细数据
     */
    private void aggregatedData(HeartRateRecord heartRateRecord, List<HeartRate> heartRates, long fristTime,long startTimp,long endTimp){
        if(heartRates==null || heartRates.size()==0){
            heartRateRecord.setHeartRateMax(0);
            heartRateRecord.setHeartRateAvg(0);
            heartRateRecord.setJsondata("[]");
            return;
        }

        int maxHR = 0;
        int totalHR = 0;
        int count = 0;
        List<Map<String,Object>> jsondate = new ArrayList<>();
        for(HeartRate heartRate : heartRates){
            long time = Long.parseLong(heartRate.getTime());
            if(startTimp<=time && time<=endTimp){
                if(maxHR < heartRate.getHr()){
                    maxHR = heartRate.getHr();
                }
                totalHR += heartRate.getHr();
                Map<String,Object> temp = new HashMap<>();
                temp.put("time", DateUtils.getStringTime(time-fristTime));
                temp.put("hr",heartRate.getHr());
                jsondate.add(temp);
                count ++;
            }
        }

        heartRateRecord.setHeartRateMax(maxHR);
        heartRateRecord.setHeartRateAvg(totalHR/count);
        heartRateRecord.setJsondata(JSONArray.toJSONString(jsondate));
    }



    /**
     * 根据水上分段表 id 和 运动员 id 查询心率
     */
    @Override
    public List<HeartRateRecord> listRS(Integer rateCountId, Integer sportsmanId) {
        return this.list(Wrappers.<HeartRateRecord>lambdaQuery()
                .eq(HeartRateRecord::getHeartRateCountId , rateCountId)
                .eq(HeartRateRecord::getSportsmanId , sportsmanId));
    }











}